package com.apkcore.core.database

import android.util.Log
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import com.apkcore.core.cp.ApkcoreContentProvider
import com.apkcore.core.util.Utils

object RoomDatabaseProvider {
    @Volatile
    private var database: RoomDatabase? = null

    fun <T : RoomDatabase> initialize(
        dbClass: Class<T>,
        dbName: String,
        callback: RoomDatabase.Callback? = null,
        migration: Migration? = null
    ): T {
        val dbPath = "${Utils.getRootPath(ApkcoreContentProvider.appContext, true)}/WaveDb/$dbName"
        Log.d("TAG", "dbPath: $dbPath")
        val factory = CustomSQLiteOpenHelperFactory(dbPath)

        return database as T? ?: synchronized(this) {
            database as T? ?: Room.databaseBuilder(
                ApkcoreContentProvider.appContext,
                dbClass,
                dbPath
            )
                .apply {
                    openHelperFactory(factory)
                    if (callback != null) {
                        addCallback(callback)
                    }
                    if (migration != null) {
                        addMigrations(migration)
                    }
                    //fallbackToDestructiveMigration() 方法，Room会自动删除旧数据库并重新创建新表。
                    fallbackToDestructiveMigration()
                    allowMainThreadQueries()
                }.build().also { database = it }
        }
    }
}
